/**
 * Copyright phonemap.com
 *
 * Licensed under the phonemap.com License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.phonemap.com/licenses/LICENSE-1.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.phonemap;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.phonemap.common.Util;
import com.phonemap.models.User;

/**
 * The Class LoginServlet.
 */
@SuppressWarnings("serial")
public class LoginServlet extends BaseServlet {
	
	/** The Constant logger. */
	private static final Logger logger = Logger.getLogger(LoginServlet.class
			.getCanonicalName());
	
	/**
	 * Get the requested photo entities in JSON format.
	 *
	 * @param req the req
	 * @param resp the resp
	 * @throws ServletException the servlet exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
		logger.log(Level.INFO, "Obtaining User listing");
		String action = req.getParameter("action");
		PrintWriter out = resp.getWriter();
		if (action.equalsIgnoreCase("checkaccount")) {
//			String phone = req.getParameter("phone");
//			String email = req.getParameter("email");
//			List<Entity> entities = new ArrayList<Entity>();
//			Entity entity = User.getUser(phone);
//			if(entity != null)
//				entities.add(entity);
//			Iterable<Entity> listEntity = User.getUsers("email", email);
//			if (listEntity != null) {
//				if (listEntity.iterator().hasNext()) 
//					entities.add(listEntity.iterator().next());
//			}
//			out.println(Util.writeJSON(entities));
		} else if (action.equalsIgnoreCase("login")) {
//			String phone = req.getParameter("phone");
//			String password = req.getParameter("password");
//			Entity entity = User.getUser(phone);
//			List<Entity> entities = new ArrayList<Entity>();
//			if (entity != null) {
//				if (password.equals(entity.getProperty("password").toString())) {
//					entities.add(entity);
//				}
//			}
//			out.println(Util.writeJSON(entities));
		} else if (action.equalsIgnoreCase("getUser")) {
			String id = req.getParameter("id");
			Entity entity = User.getUser(Long.parseLong(id));
			List<Entity> entities = new ArrayList<>();
			if (entity != null) {
				entities.add(entity);
			}
			out.println(Util.writeJSON(entities));
		}
		
		return;
	}

	/**
	 * Insert the new customer.
	 *
	 * @param req the req
	 * @param resp the resp
	 * @throws ServletException the servlet exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.log(Level.INFO, "Creating User");
		
//		String phone = req.getParameter("phone");
//		String email = req.getParameter("email");
//		String password = req.getParameter("password");
//		User.insertUser(id, fullname, link, birthday, interested_in, gender, email, relationship_status, timezone, locale, verified, updated_time, username, password, phone)
//		User.createOrUpdateUser(id, name, first_name, last_name, 
//								link, birthday, interested_in, relationship_status, 
//								website, timezone, locale, verified, 
//								updated_time, username);
//		User.createOrUpdateUser(phone, null, null, 
//				null, null, null, null, 
//				email, null, null, 
//				null, null, null, null, 
//				null, password);
	}

	/**
	 * Delete the customer.
	 *
	 * @param req the req
	 * @param resp the resp
	 * @throws ServletException the servlet exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String phone = req.getParameter("id");
		logger.log(Level.INFO, "Deleting User {0}", phone);
		Key key = KeyFactory.createKey("User", phone);
		try {
			// CASCADE_ON_DELETE
			Iterable<Entity> entities = Util.listChildKeys("Position", key);
			final List<Key> positionkeys = new ArrayList<Key>();
			for (Entity e : entities) {
				positionkeys.add(e.getKey());

			}
			Util.deleteEntity(positionkeys);
			Util.deleteFromCache(key);
			Util.deleteEntity(key);
		} catch (Exception e) {
			String msg = Util.getErrorResponse(e);
			resp.getWriter().print(msg);
		}
	}

	/**
	 * Redirect the call to doDelete or doPut method.
	 *
	 * @param req the req
	 * @param resp the resp
	 * @throws ServletException the servlet exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = req.getParameter("action");
		if (action.equalsIgnoreCase("delete")) {
			doDelete(req, resp);
			return;
		} else if (action.equalsIgnoreCase("put")) {
			doPut(req, resp);
			return;
		}
	}
	
	/**
	 * Login.
	 *
	 * @param req the req
	 * @param resp the resp
	 * @throws ServletException the servlet exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	protected void doLoginWithFacebook(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.log(Level.INFO, "Creating User");
		
//		String user_id = req.getParameter("id");
//		Entity user = User.getUser(user_id);
		
	}
	
	
}
